package net.lzzy.practices.aspects;

import net.lzzy.practices.entities.User;
import net.lzzy.practices.services.UserService;
import net.lzzy.practices.utils.AspectUtil;
import net.lzzy.practices.utils.JwtUtil;
import net.lzzy.practices.web.models.ApiResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.Arrays;

import java.util.UUID;

/**
 * @author damin
 */
@Aspect
@Component
public class AdminAspect {

    @Autowired
    private final UserService service;

    public AdminAspect(UserService service){
        this.service=service;
    }
    //*代表拦截，如软件包有多个控制层* 包下的所有类，如：net.lzzy.practices.web.admin.*
    @Pointcut("execution(* net.lzzy.practices.web.admin.UserApiController.*(..))")
    public void adminPoint(){}
    //将切面点放入aroud
    @Around("adminPoint()")
    public ApiResult aroundAdminController(ProceedingJoinPoint point) throws Throwable {
        //token参数的3种形式：1.直接列在方法参数中，2.使用了Info参数类BaseInfo，3.使用JSONObject对象
        String token= AspectUtil.getToken(point);
        String uid = JwtUtil.verifyToken(token);
        if (uid==null){
            return new ApiResult(false,"认证信息已失效，请重新登录！",null);
        }

        User user = service.getById(UUID.fromString(uid));

        if (user==null){
            return new ApiResult(false,"认证信息无效，请登录！",null);
        }
        //允许访问接口的身份
        int[] allowRoles = new  int[]{User.TYPE_ADMIN};
        if (Arrays.stream(allowRoles).noneMatch(role -> role==user.getType())){
            return new ApiResult(false,"没有权限,请登录为管理员！",null);
        }

        return (ApiResult) point.proceed();
    }
}
